package com.bea.ftd.dashboard.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bea.ftd.common.ValidationException;
import com.bea.ftd.common.dao.ApiDefineRepo;
import com.bea.ftd.common.dao.MsgInConfRepo;
import com.bea.ftd.common.dao.PartnerInfoRepo;
import com.bea.ftd.common.entity.ApiDefine;
import com.bea.ftd.common.entity.MsgInConf;
import com.bea.ftd.common.entity.PartnerInfo;
import com.bea.ftd.common.enums.ValidationErrorCode;
import com.bea.ftd.common.utils.XmlUtils;
import com.bea.ftd.dashboard.service.IGatewayService;
import com.bea.ftd.dashboard.service.IMsgInConfService;
import com.bea.ftd.dashboard.validator.BooleanValidator;
import com.bea.ftd.dashboard.validator.CustomTypeValidator;
import com.bea.ftd.dashboard.validator.NumberValidator;
import com.bea.ftd.dashboard.validator.StringValidator;
import com.google.gson.Gson;

@Service
public class MsgInConfServiceImpl implements IMsgInConfService, IGatewayService {
	private Logger LOGGER = LoggerFactory.getLogger(MsgInConfServiceImpl.class);

	@Autowired
	private StringValidator stringValidator;
	@Autowired
	private BooleanValidator booleanValidator;
	@Autowired
	private NumberValidator numberValidator;
	@Autowired
	private CustomTypeValidator customTypeValidator;

	@Autowired
	private MsgInConfRepo msgInConfRepo;
	@Autowired
	private ApiDefineRepo apiDefineRepo;

	@Autowired
	private PartnerInfoRepo partnerInfoRepo;

	@Override
	public void addMsgInConf(MsgInConf msgInConf) throws ValidationException {
		validateInputParams(msgInConf);
		setCreateOrUpdateTime(msgInConf, msgInConfRepo);
		msgInConfRepo.save(msgInConf);
	}

	/**
	 * 验证输入参数是否有效
	 * 
	 * @param msgInConf
	 * @throws ValidationException
	 */
	private void validateInputParams(MsgInConf msgInConf) throws ValidationException {

		if (stringValidator.isEmptyString(msgInConf.getApiId())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "API ID不能为空");
		}


		if (stringValidator.isEmptyString(msgInConf.getParamName())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "参数名不能为空");
		}

		if (stringValidator.isEmptyString(msgInConf.getParamNote())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "参数注释不能为空");
		}

		if (stringValidator.isEmptyString(msgInConf.getParamType())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "参数类型不能为空");
		}

		if (!numberValidator.isNonNegtiveNumber(msgInConf.getParamLength())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "参数长度必须为大于等于0的值");
		}

		if (!booleanValidator.isBooleanType(msgInConf.getIsActivated())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "无效的isActivated值");
		}

		if (!booleanValidator.isBooleanType(msgInConf.getIsEmpty())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "无效的isEmpty值");
		}

		if (!customTypeValidator.isValidEncryptStrategy(msgInConf.getEncryptStrategy())) {
			throw new ValidationException(ValidationErrorCode.EMPTY_VALUE, "无效的加密策略");
		}

	}

	@Override
	public List<MsgInConf> getAllMsgInConfs() {
		try {
			return msgInConfRepo.findAll();
		} catch (Exception e) {
			LOGGER.error("error when querying msgInConf from database " + e.getMessage());
			return null;
		}
	}

	@Override
	@Transactional
	public void addMsgInConfFromExample(String exampleData, String apiId) throws Exception {
		ApiDefine apiDefine = apiDefineRepo.findById(apiId).get();
		String partnerCode = apiDefine.getParnterCode();
		PartnerInfo partnerInfo = partnerInfoRepo.findByPartnerCode(partnerCode);
		String dataType = partnerInfo.getMsgInType();
		msgInConfRepo.deleteByApiId(apiId);
		if (dataType.equalsIgnoreCase("xml")) {
			Map<String, Object> map = XmlUtils.Xml2Map(exampleData);
			saveMsgInConf(map, apiId,"");

		} else if (dataType.equalsIgnoreCase("json")) {
			Gson gson = new Gson();
			Map<String, Object> map = gson.fromJson(exampleData, Map.class);
			saveMsgInConf(map, apiId,"");
		}
		
	}
	
	private void saveMsgInConf(Map<String, Object> map, String api_id,String parent) throws Exception {

		int size = map.keySet().size();
		List<String> keylist = new ArrayList<>();

		for (String key : map.keySet()) {
			String type = map.get(key).getClass().getName();
			MsgInConf msgInConf = new MsgInConf();
			msgInConf.setApiId(api_id);
			msgInConf.setParamName(key);
			msgInConf.setEncryptStrategy((long) 0);
			msgInConf.setParamLength((long) 255);
			msgInConf.setIsActivated((long) 1);
			msgInConf.setCreateTime(new Date());
			msgInConf.setParamType(type);
			msgInConf.setIsEmpty((long) 0);
			msgInConf.setUpdateTime(new Date());
			msgInConf.setParamNote("");
			msgInConf.setParentNode(parent);
			msgInConfRepo.save(msgInConf);

			if(type.equals("java.util.LinkedHashMap")){
				size--;
				keylist.add(key);
			}else{
				size--;
			}

		}
		if(size == 0){
			for(String keyone:keylist){
				parent = keyone;
				saveMsgInConf((Map)map.get(keyone),api_id,parent);
			}

		}
	}

	@Transactional
	@Override
	public void deleteMsgInConfContent(String apiId) {
		msgInConfRepo.deleteByApiId(apiId);
	}
}
